package com.own.system.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.own.system.entity.User;
import com.own.system.mapper.UserMapper;
import com.own.system.service.UserService;
import com.own.system.utils.SystemConstants;
import com.own.system.vo.query.UserQueryVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author anonymous
 * @since 2024-08-15
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    /**
     * 根据用户名查询用户信息
     *
     * @param username
     * @return
     */

    @Override
    public User findUserByUserName(String username) {
        //创建条件构造器对象
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.eq("username", username);
        //查询
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 分页查询用户列表
     * @param page
     * @param userQueryVo
     * @return
     */
    @Override
    public IPage<User> findUserListByPage(IPage<User> page, UserQueryVo userQueryVo) {
        //创建条件构造器对象
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        //部门编号
        queryWrapper.eq(!ObjectUtils.isEmpty(userQueryVo.getDepartmentId()), "department_id", userQueryVo.getDepartmentId());
        //用户名
        queryWrapper.like(!ObjectUtils.isEmpty(userQueryVo.getUsername()), "username", userQueryVo.getUsername());
        //真实姓名
        queryWrapper.like(!ObjectUtils.isEmpty(userQueryVo.getRealName()), "real_name", userQueryVo.getRealName());
        //电话
        queryWrapper.like(!ObjectUtils.isEmpty(userQueryVo.getPhone()), "phone", userQueryVo.getPhone());
        //        查询并返回数据
        return baseMapper.selectPage(page, queryWrapper);
    }

    /**
     * 删除用户
     * @param id
     * @return
     */

    @Override
    @Transactional(rollbackFor = RuntimeException.class)//抛出异常回滚
    public boolean deleteById(Long id) {
        //查询
        User user=baseMapper.selectById(id);
        //删除用户角色关系
        baseMapper.deleteUserRole(id);
        //删除用户
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean saveUserRole(Long userId, List<Long> roleIds) {
        //删除该用户对应的角色信息
        baseMapper.deleteUserRole(userId);
        return baseMapper.saveUserRole(userId, roleIds)>0;
    }
}
